set -x
ENGINE=${1:-vllm}

export HF_ENDPOINT=https://hf-mirror.com
export HYDRA_FULL_ERROR=1
RAY_DEBUG=1
# export GLOO_SOCKET_IFNAME=bond0
export VLLM_USE_V1=1
# export RAY_JOB_CONFIG_JSON_ENV_VAR=\{\"HF_ENDPOINT\":\"https://hf-mirror.com\",\"VLLM_USE_V1\":\"1\",\"RAY_DEBUG\":\"1\"}

env_name=ascend_large
env_name=ascend_debug
# env_name=cuda_debug

DATE=$(date +%Y%m%d_%H%M%S)
project_name="toolbench"
experiment_name="grpo_qwen2.5_32b_$DATE"

clip_ratio_low=0.2
clip_ratio_high=0.28
enable_filter_groups=True
max_num_gen_batches=10


if [ "$env_name" = "ascend_large" ]; then
    group_size=4
    node_num=2
    dev_num=8
    train_data_size=`expr $node_num \* 8`
    val_data_size=`expr $node_num \* 8`
    # ppo_mini_batch_size=`expr $node_num \* 8`
    ppo_mini_batch_size=16
    train_files=/mnt/nas/users/wangmin/agentic_system_r/agentic_system/environments/env_package/mirrorapi/data_processor/g3_hf_dataset/test.parquet
    val_files=/mnt/nas/users/wangmin/agentic_system_r/agentic_system/environments/env_package/mirrorapi/data_processor/g3_hf_dataset/test.parquet
    model=/mnt/nas/huggingface_hub/models--Qwen--Qwen2.5-32B-Instruct
    model=/mnt/nas/huggingface_hub/models/Qwen/Qwen3-4B-Instruct-2507
    reward_fn_path=/mnt/nas/tianye/code/agentic_system_r/agentic_system/experimental/swe_reward.py
    VLLM_ATTENTION_BACKEND=FLASH_ATTN_VLLM_V1
    tp=8
    cp=1
    GLOO_SOCKET_IFNAME=bond0
    device=npu
    export HUGGINGFACE_HUB_CACHE="/mnt/nas/huggingface_hub/"
    export TENSORBOARD_DIR="/mnt/nas/tianye/agenticmodel/log/$project_name/$experiment_name/"
    max_turn=20
elif [ "$env_name" = "ascend_debug" ]; then
    train_data_size=8
    val_data_size=2
    group_size=1
    node_num=1
    dev_num=1
    ppo_mini_batch_size=1
    train_files=/mnt/nas/users/wangmin/agentic_system_r/agentic_system/environments/env_package/mirrorapi/data_processor/g3_hf_dataset/test.parquet
    val_files=/mnt/nas/users/wangmin/agentic_system_r/agentic_system/environments/env_package/mirrorapi/data_processor/g3_hf_dataset/test.parquet
    model=/mnt/nas/huggingface_hub/models--Qwen--Qwen2.5-0.5B-Instruct
    model=/mnt/nas/huggingface_hub/models/Qwen/Qwen3-0___6B
    # model=/mnt/nas/huggingface_hub/models/Qwen/Qwen3-4B-Instruct-2507
    export HUGGINGFACE_HUB_CACHE="/home/tianye/hf_dir/"
    reward_fn_path=/mnt/nas/tianye/code/agentic_system_r/agentic_system/experimental/swe_reward.py
    tp=1
    cp=1
    # export VLLM_ATTENTION_BACKEND=XFORMERS
    VLLM_ATTENTION_BACKEND=FLASH_ATTN_VLLM_V1
    device=npu
    GLOO_SOCKET_IFNAME=bond0

    export TENSORBOARD_DIR="/mnt/nas/tianye/agenticmodel/log/$project_name/$experiment_name/"
    max_turn=20
elif [ "$env_name" = "cuda_debug" ]; then
    train_data_size=2
    val_data_size=2
    group_size=2
    node_num=1
    dev_num=1
    ppo_mini_batch_size=2
    train_files=swe_bench_verified_train.parquet
    val_files=swe_bench_verified_test.parquet
    model=/home/tianye/hf_dir/models--Qwen--Qwen2.5-0.5B-Instruct
    export HUGGINGFACE_HUB_CACHE="/home/tianye/hf_dir"
    reward_fn_path=agentic_system/experimental/swe_reward.py
    export TENSORBOARD_DIR="/mnt/nas/tianye/agenticmodel/log/$project_name/$experiment_name/"
    tp=1
    VLLM_ATTENTION_BACKEND=FLASH_ATTN_VLLM_V1
    max_turn=2
    device=cuda
    GLOO_SOCKET_IFNAME=enp4s0
    cp=1
fi
# unset VLLM_ATTENTION_BACKEND
agent_worker_num=`expr $node_num \* $dev_num`


rollout_mode="async"
if [ "$rollout_mode" = "async" ]; then
    return_raw_chat="True"
fi


# We only use data preparation to indicate the modality and the data size.
# python3 -m environments.env_package.mirroapi.data_preprocess.prepare \
# python3 -m environments.env_package.mirrorapi.data_processor.process_data \
# python3 agentic_system/environments/env_package/mirrorapi/data_processor/process_data.py
#     # --mode 'text' \
#     # --train_data_size $train_data_size \
#     # --val_data_size $val_data_size \
#     # --local_dir /mnt/nas/tianye/data/verl-agent 
# exit 0
    # data.train_files=/mnt/nas/tianye/data/verl-agent/text/test.parquet \
    # data.val_files=/mnt/nas/tianye/data/verl-agent/text/test.parquet \
# /mnt/nas/huggingface_hub/models/Qwen/Qwen3-0___6B
# /mnt/nas/huggingface_hub/models--Qwen--Qwen2.5-0.5B-Instruct

python3 -m agentic_system.main_ppo \
    algorithm.adv_estimator=grpo \
    data.train_files=$train_files \
    data.val_files=$val_files \
    data.prompt_key="query" \
    data.train_batch_size=$train_data_size \
    data.val_batch_size=$val_data_size \
    data.return_raw_chat=$return_raw_chat \
    data.max_prompt_length=2000 \
    data.max_response_length=1024 \
    data.filter_overlong_prompts=False \
    data.truncation='middle' \
    data.return_raw_chat=True \
    actor_rollout_ref.model.path=$model \
    actor_rollout_ref.model.trust_remote_code=True \
    actor_rollout_ref.actor.optim.lr=1e-6 \
    actor_rollout_ref.model.use_remove_padding=True \
    actor_rollout_ref.actor.use_torch_compile=False \
    actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=1 \
    actor_rollout_ref.actor.use_kl_loss=True \
    actor_rollout_ref.actor.kl_loss_coef=0.01 \
    actor_rollout_ref.actor.kl_loss_type=low_var_kl \
    actor_rollout_ref.actor.clip_ratio_low=${clip_ratio_low} \
    actor_rollout_ref.actor.clip_ratio_high=${clip_ratio_high} \
    actor_rollout_ref.actor.ulysses_sequence_parallel_size=$cp \
    actor_rollout_ref.ref.ulysses_sequence_parallel_size=$cp \
    actor_rollout_ref.model.enable_gradient_checkpointing=True \
    actor_rollout_ref.actor.fsdp_config.param_offload=False \
    actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
    actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=1 \
    actor_rollout_ref.rollout.tensor_model_parallel_size=$tp \
    actor_rollout_ref.rollout.max_model_len=16384 \
    actor_rollout_ref.rollout.multi_turn.max_assistant_turns=$max_turn \
    actor_rollout_ref.rollout.name=$ENGINE \
    actor_rollout_ref.rollout.n=$group_size \
    actor_rollout_ref.rollout.mode=$rollout_mode \
    actor_rollout_ref.rollout.gpu_memory_utilization=0.47 \
    actor_rollout_ref.rollout.enable_chunked_prefill=True \
    actor_rollout_ref.rollout.enforce_eager=False \
    actor_rollout_ref.rollout.load_format=auto \
    actor_rollout_ref.rollout.free_cache_engine=False \
    actor_rollout_ref.rollout.val_kwargs.temperature=0.4 \
    actor_rollout_ref.rollout.val_kwargs.do_sample=True \
    actor_rollout_ref.rollout.prompt_length=6000 \
    actor_rollout_ref.rollout.response_length=2048 \
    actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=1 \
    actor_rollout_ref.ref.fsdp_config.param_offload=True \
    actor_rollout_ref.actor.ppo_mini_batch_size=$ppo_mini_batch_size \
    ++algorithm.use_kl_in_reward=False \
    +algorithm.filter_groups.enable=${enable_filter_groups} \
    +algorithm.filter_groups.max_num_gen_batches=${max_num_gen_batches} \
    +env.env_name=toolbench \
    +env.seed=0 \
    +env.max_steps=2 \
    +env.rollout.n=$group_size \
    trainer.critic_warmup=0 \
    trainer.logger=['console',"tensorboard"] \
    trainer.project_name="$project_name" \
    trainer.experiment_name="$experiment_name" \
    trainer.default_local_dir="/mnt/nas/tianye/agenticmodel/checkpoints/$project_name/$experiment_name" \
    trainer.rollout_data_dir="/mnt/nas/tianye/agenticmodel/log/$project_name/$experiment_name/rollout" \
    trainer.validation_data_dir="/mnt/nas/tianye/agenticmodel/log/$project_name/$experiment_name/val" \
    +trainer.tensorboard_dir="/mnt/nas/tianye/agenticmodel/log/$project_name/$experiment_name/" \
    +ray_kwargs.ray_init.runtime_env.env_vars.HF_ENDPOINT=https://hf-mirror.com \
    +ray_kwargs.ray_init.runtime_env.env_vars.VLLM_USE_V1=\"1\" \
    +ray_kwargs.ray_init.runtime_env.env_vars.RAY_DEBUG=\"$RAY_DEBUG\" \
    +ray_kwargs.ray_init.runtime_env.env_vars.HUGGINGFACE_HUB_CACHE=$HUGGINGFACE_HUB_CACHE \
    +ray_kwargs.ray_init.runtime_env.env_vars.TENSORBOARD_DIR=/mnt/nas/tianye/agenticmodel/log/$project_name/$experiment_name/ \
    +ray_kwargs.ray_init.runtime_env.env_vars.GLOO_SOCKET_IFNAME=$GLOO_SOCKET_IFNAME \
    +ray_kwargs.ray_init.runtime_env.env_vars.RAY_IGNORE_UNHANDLED_ERRORS=\"1\" \
    +ray_kwargs.ray_init.runtime_env.env_vars.VLLM_ATTENTION_BACKEND=$VLLM_ATTENTION_BACKEND \
    trainer.device=$device \
    trainer.n_gpus_per_node=$dev_num \
    trainer.nnodes=$node_num \
    trainer.save_freq=-1 \
    trainer.test_freq=5 \
    trainer.total_epochs=150 \
    trainer.balance_batch=False \
    trainer.val_before_train=False 2>&1 | tee debug.log
